﻿using Admin.Auth.Dto;
using Admin.Repository.MenuRoles;
using Admin.Repository.Menus;
using CSRedis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Admin.Auth
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 自定义授权过滤器
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //实现自定义授权
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new StatusCodeResult(401);
            }

            ////获取当前用户角色
            var role = context.HttpContext.User.Claims.Where(x => x.Type == ClaimTypes.Role)
                        .Select(x => Convert.ToInt32(x.Value)).ToArray();

            //当前用户正在访问的path
            var routeInfo = context.ActionDescriptor.AttributeRouteInfo.Template;

            var serviceProvicer = context.HttpContext.RequestServices;

            var menuRoleRepo = serviceProvicer.GetService(typeof(IMenuRoleRepository)) as IMenuRoleRepository;
            var menuRepo = serviceProvicer.GetService(typeof(IMenuRepository)) as IMenuRepository;
                        
            //Redis
            var redis = serviceProvicer.GetService(typeof(CSRedisClient)) as CSRedisClient;
            //Redis添加菜单角色信息
            var redismenuRole = redis.Set($"menuRoleRepo:menuRole", menuRoleRepo.Queryable());
            //Redis添加角色信息
            var redismenu = redis.Set($"menuRepo:menu", menuRepo.Queryable());
            //Redis查询菜单角色信息
            var GetredismenuRole = redis.Get<List<MenuRoleDto>>($"menuRoleRepo:menuRole");
            //Redis查询角色信息
            var Getredismenu = redis.Get<List<MenuDto>>($"menuRepo:menu");

            if (GetredismenuRole == null || Getredismenu == null)
            {
                throw new Exception("Getredismenu/Getredismenu获取失败！");
            }

            //查询
            var list = GetredismenuRole.Where(x => x.MenuId == Getredismenu.Where(x => x.Path == routeInfo).First().MenuId).Select(x => x.RoleId).ToArray();

            //var list1 = menuRepo.Queryable().Join(menuRoleRepo.Queryable(), a => a.MenuId, b => b.MenuId, (a, b) => new { a, b, }).Where(x => x.a.Path == routeInfo).Select(x => x.b.RoleId).ToArray();

            //var data=

            if (!list.Any(x => role.Contains(x)))
            {
                context.Result = new StatusCodeResult(403);
            }
        }
    }
}
